<?php

namespace App\Http\Controllers;

use App\Http\Requests\CardCreate;
use App\Http\Requests\CardUpdate;
use App\Models\Card;
use Illuminate\Http\Request;

class CardController extends Controller
{
    public function list(Request $request){
        $limit = $request->limit ?? 10;
        $res = Card::where([
            'school_id' => $request->school_id,
            'campus_id' => $request->campus_id
        ])->paginate($limit);
        return resSucc(formatPage($res), "学员卡列表");
    }

    public function simpleList(Request $request){
        $res = Card::where([
            'school_id' => $request->school_id,
            'campus_id' => $request->campus_id
        ])->get();
        return resSucc($res, "学员卡列表");
    }

    public function create(CardCreate $request){

        $card = $request->validated();
        $card['school_id'] = $request->school_id;
        $card['campus_id'] = $request->campus_id;

        try{
            $res = Card::create($card);
            return resSucc($res, "创建成功");
        } catch (\Exception $e) {
            return resFail($e, "创建失败");
        } catch (\Throwable $e) {
            return resFail($e, "创建失败");
        }

    }

    public function update(CardUpdate $request){

        $card = $request->validated();
        $id = $card['card_id'];
        unset($card['card_id']);
        try{
            $res = Card::where('id', $id)->update($card);
            return resSucc($res, "更新成功");
        } catch (\Exception $e) {
            return resFail($e, "更新失败");
        } catch (\Throwable $e) {
            return resFail($e, "更新失败");
        }

    }

    public function info(Request $request, $id) {
        $school_id =  $request->school_id;
        $campus_id = $request->campus_id;
        $res = Card::where([
            'school_id' => $school_id,
            'campus_id' => $campus_id,
            'id' => $id,
        ])->first();
        return resSucc($res, "学员卡详情");
    }
}
